
//  TMBView.m
//  TouchMeBaby
//
//  Created by 丁诚昊(831) on 15-6-8.
//  Copyright (c) 2015年 丁诚昊(831). All rights reserved.
//

#import "DCH_3DSpaceLear.h"
#import "UIView+D_Geometry.h"
#include <stdlib.h>

#if TARGET_OS_IOS
#define miniumRadius 3
#define DotsCountInSmallView 6

#define __WeakSelf(Class) __weak typeof(&*Class) WS_Objc = self;
#endif

///随机暗色
#define RandomColorDark [UIColor colorWithRed:12.f green:12.2 blue:12.f alpha:.9f]

int arc4random_range(int start,int end)
{
    int offset = abs(end - start);
    return arc4random_uniform(offset) + start;
}

typedef NSUInteger DotsCount;
static CGFloat _radius;

@interface DCH_3DSpaceLear ()
/**毛玻璃*/
@property (nonatomic,weak) UIVisualEffectView* blurCover;
@end

@implementation DCH_3DSpaceLear
// 随机生成一个SpaceView指针
+(instancetype) fancyColorCypherView
{
    DCH_3DSpaceLear* colorfullDay = [[DCH_3DSpaceLear alloc] init];
    colorfullDay.backgroundColor = [UIColor clearColor];
    colorfullDay.userInteractionEnabled = YES;
    return colorfullDay;
}

#pragma mark -- Private & 2D DrawRect
/**
 * 画一个⭕️ 嘻嘻哈哈 🐩🐩🐶🐱🐈🐈
 */
- (void)drawRect:(CGRect)rect {
    //1.获取bit位图上下文
    CGSize bitMapSize = self.bounds.size;
    CGFloat scaleValue = 1.f;
    UIGraphicsBeginImageContextWithOptions(bitMapSize, NO, scaleValue);
    //2.开始画图到上下文中
    CGContextRef ccr = UIGraphicsGetCurrentContext();
    [[UIView randomColor] set];
    CGContextFillEllipseInRect(ccr, self.bounds);
    UIImage* BitMapImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //3.关闭上下文
    UIGraphicsEndImageContext();
    
    [self setBackgroundImage:BitMapImage forState:UIControlStateNormal];
    [self setBackgroundImage:BitMapImage forState:UIControlStateSelected];
    
    //把临时数据图片写入桌面11文件夹
    NSData* data = UIImagePNGRepresentation(BitMapImage);
    NSString* fileName = [NSString stringWithFormat:@"丁诚昊制作BitMap位图-%p.jpg",self.description];
    fileName = [@"/Users/DCH831/Desktop/bitmap" stringByAppendingPathComponent:fileName];
    [data writeToFile:fileName atomically:YES];
}

#pragma mark - longPressGesture
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self setHighlighted:YES];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
    
    [self setSelected:YES];
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    [self touchesCancelled:touches withEvent:event];
}

/// 太小的粒子长按会被放大
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    CGRect TouchesBounds = self.bounds;
    if (_radius < miniumRadius ) {
        CGFloat extensionRange = miniumRadius - _radius;
        TouchesBounds = CGRectInset(TouchesBounds, -extensionRange, -extensionRange);
    }
    return CGRectContainsPoint(TouchesBounds, point);
}

#pragma mark -- private methods
// 随机生成一个静态指针
+(instancetype) randomDotView{
    DCH_3DSpaceLear* dots = [[DCH_3DSpaceLear alloc] init];
    dots.backgroundColor = [UIColor clearColor];
    dots.userInteractionEnabled = YES;
    return dots;
}

+ (void) arrangeDotsLikeACycle:(UIView *)view withR:(CGFloat)R PivotX:(unsigned short)N
{
    ///1.矩阵放大
    int pivot = arc4random_range(N, pow(N, N));
    NSLog(@"pivot 量子%zd刀 : 矩阵拉伸--->%zd",N,pivot);
    
    ///0.定义量子切片儿
    if(R <= pivot){
        NSLog(@"死切:---> R <= pivot");
        return;
    }
    int _radius = R / pivot;
    
    ///1.选一个中心点图标
    CGPoint CenterPoint = CGPointMake(view.D_Width/2, view.D_Height/2);
    DCH_3DSpaceLear* Dots = view.subviews[arc4random_uniform((u_int32_t)view.subviews.count)];
    __block __weak DCH_3DSpaceLear *ptrCen;
    
    if([Dots isKindOfClass:[DCH_3DSpaceLear class]])
    {
        ///2.首先移动一个点到中心点坐标
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            
            Dots.frame = CGRectMake(0,0,view.D_Width*.2f, view.D_Width*.2f);
            Dots.D_CenterX = kscreemWidth  / 4;
            Dots.D_CenterY = kscreemHeight / 4;
            ptrCen = Dots;
            [ptrCen RenderWithCGImage:@"eye-512.png"];
        });
    }
    
    CGPoint lineOfPoints[view.subviews.count];    ///buffer[frames] 矩阵点的缓存数组
    
    //一次算出所有的轨迹点。。。
    unsigned int counter = 0;
    ///推理机： 这个关键性的圆周率划分 非常有意思！请记得变更这个阀值 这里有3D矩阵的入口
    while ( R >= _radius*2 )
    {
        for (CGFloat startPointX = -R; startPointX <= R; startPointX += 1 && counter<=618)
        {
            for (CGFloat startPointY = -R; startPointY <= R; startPointY +=1)
            {
                if(pow(startPointX, 2)+pow(startPointY, 2) == pow(R, 2))
                {
                    lineOfPoints[counter] = CGPointMake(CenterPoint.x+startPointX, CenterPoint.y+startPointY);
                    counter++;
                }
            }
        }
        
        R -= _radius;/**五行八卦 金木水火土*/;
    }
    
    NSLog(@" Numbers = ^%zd",counter);
    
    for (int i = 1; i < counter ; i++)
    {
        UIView* subView = view.subviews[i];
        
        if(subView == ptrCen)
        {
            i++;
            continue;
        }
        
        if([subView isKindOfClass:[DCH_3DSpaceLear class]]){
            CGPoint pointPtr = lineOfPoints[i];
            subView.frame=CGRectMake(pointPtr.x-_radius,
                                     pointPtr.y-_radius,
                                     (_radius+i/pivot),
                                     (_radius+i/pivot)
                                     ); //衰变放大
        }
    }
    
    
    /// 👀 动效
    CGFloat slashTime = .5f;
    __weak typeof(UIView) *superView = ptrCen.superview;
    
    
    DCH_3DSpaceLear* copyEye = (DCH_3DSpaceLear*)[[UIImageView alloc ] initWithImage:[UIImage imageNamed:@"eye-512.png"]];
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [UIView animateWithDuration:slashTime animations:^{
            superView.backgroundColor = [UIColor lightGrayColor];
            ///👀一分为二 左右排布 v0.1版本为图片 以后可以用Quartz2D手绘 TODO：让眼球充满血丝 哈哈！！！
            
            [superView addSubview:copyEye];
        }completion:^(BOOL finished) {
            [UIView animateWithDuration:slashTime
                                  delay:0
                                options:UIViewAnimationOptionOverrideInheritedDuration
                             animations:^{
                                 [superView bringSubviewToFront:ptrCen];
                                 superView.backgroundColor = [UIColor blackColor];
                                 copyEye.frame = ptrCen.frame;
                             } completion:^(BOOL finished) {
                                 [UIView animateWithDuration:slashTime animations:^{
                                     copyEye.D_Left = kscreemWidth - ptrCen.D_Left - ptrCen.D_Width;
                                 }];
                             }];
        }];
    });
}

/**顺序排布子控件和随机排布子控件 TODO：应该拆分成俩个方法 1随机 2线性 */
+ (void)arrangeDotsRandomlyInView:(UIView *)view{
    //当视图是主屏幕的子视图切大小小于主屏幕宽高时更改计算方式
    if(view.D_Height == kscreemHeight){
        for (UIView* subview in view.subviews) {//一种随机排布算法
            _radius = arc4random_range(miniumRadius, miniumRadius*2);
            CGRect bounds = CGRectMake(arc4random_range(0, view.bounds.size.width-_radius*2),arc4random_range(0, view.bounds.size.height-_radius*2),_radius*2,_radius*2);
            if([subview isKindOfClass:[DCH_3DSpaceLear class]]){
                subview.frame = bounds;
            }
        }
    }else{
        DotsCount padding = kscreemWidth / 15;
        int squareRadius = (view.D_Size.width - padding*2) / DotsCountInSmallView;
        for (int i = 0; i < view.subviews.count; i++) {
            UIView* subView = view.subviews[i];
            _radius = arc4random_range(0, squareRadius);
            CGRect bounds = {{0,0},{_radius,_radius}};
            if([subView isKindOfClass:[DCH_3DSpaceLear class]])
                subView.frame = bounds;
        }
        [DCH_3DSpaceLear arrangeDotsNiftyWithAnimation:view];
    }
}

+ (void) arrangeDotsNiftyWithAnimation:(UIView*)view{
    CGFloat padding = kscreemWidth / 15;
    CGFloat squareRadius = (view.D_Size.width - padding*2) / 6;
    for (int i = 0; i < view.subviews.count; i++) {
        UIView* subView = view.subviews[i];
        [UIView animateWithDuration:.8f animations:^{
            if([subView isKindOfClass:[DCH_3DSpaceLear class]]){
                subView.D_CenterX = padding + i % DotsCountInSmallView * squareRadius + squareRadius / 2;
                subView.D_CenterY = padding + i / DotsCountInSmallView * squareRadius + squareRadius / 2;
            }
        }];
    }
}

#pragma mark - Misc &
/**滑动出来一块毛玻璃*/
+(void) lightEnSuperContranerViewWithBlurEffect:(UIView*)father
{
    UIVisualEffectView *blurView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    [father addSubview:blurView];
    blurView.frame = (CGRect){{kscreemWidth/2,kscreemHeight/2},{1,1}};
}

@end

